import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message
} from 'antd';
import GoodsCategoryTable from '../../../components/goods/goodsCategory';
import GoodsCategoryEdit from '../../../components/goods/goodsCategory/GoodsCategoryEdit';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import RecObjectAdd from '../../../components/Operation/RecObject/RecObjectAdd'

import styles from './GoodsCategory.less';
import {powerControl} from '../../../utils/powerControl';
const AuthButton = powerControl(Button);
const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
    rule: state.goodsCategory,
}))
@Form.create()
export default class GoodsCategory extends PureComponent {
    state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        record: {},
        editType: 'add',
        recObjectVisible:false,

    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsCategory/fetch',
        });
    }

    /**
     * 推荐对象模态框显示
     * @param flag
     */
    handlerecObjectVisible = (flag) => {
        this.setState({
            recObjectVisible: !!flag,
        })
    };

    /**
     * 推荐按钮事件
     * @param record
     * @param pagination
     */
    handleRecommendRow = (record, pagination) => {
        this.handlerecObjectVisible(true);
        this.setState({
            editType: 'add',
            record: record
        });
    }

    handleGoodsCategoryTableChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'goodsCategory/fetch',
            payload: params,
        });
    }

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'goodsCategory/fetch',
            payload: {},
        });
    }

    handleMenuClick = (e) => {
        const {dispatch} = this.props;
        const {selectedRows} = this.state;

        if (!selectedRows) return;

        switch (e.key) {
            case 'remove':
                dispatch({
                    type: 'goodsCategory/remove',
                    payload: {
                        no: selectedRows.map(row => row.no).join(','),
                    },
                    callback: () => {
                        this.setState({
                            selectedRows: [],
                        });
                    },
                });
                break;
            default:
                break;
        }
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    }

    handleSearch = (e) => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'goodsCategory/fetch',
                payload: values,
            });
        });
    }
    /**
     * 推荐对象新增提交
     */
    handleRecObjectAdd = () => {
        this.props.dispatch({
            type: 'recObject/add',
            payload: {
                description: this.state.addInputValue,
            },
        });
        message.success('添加成功');
        this.setState({
            recObjectVisible: false,
        });

    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    }
    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        this.setState({
            modalVisible: false,
        });
        dispatch({
            type: 'goodsCategory/fetch',
            payload: params,
        });
    }
    handleDelCategoryRow = (catId, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsCategory/del',
            payload: {cat_id: catId},
            callback: (response) => {
                if (response.result === 0) {
                    message.success('删除成功');
                    this.handleModalSuccess(pagination);
                } else {
                    message.success('删除失败');
                }
            }
        });
    }
    handleAddCategory = () => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'add',
        });
    }
    handleEditCategoryRow = (record, pagination) => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record
        });
    }
    handleAdd = () => {
        this.props.dispatch({
            type: 'goodsCategory/add',
            payload: {
                description: this.state.addInputValue,
            },
        });

        message.success('添加成功');
        this.setState({
            modalVisible: false,
        });
    }

    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="分类名称">
                            {getFieldDecorator('cat_name')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="使用状态">
                            {getFieldDecorator('cat_sts')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    <Option value="">请选择</Option>
                                    <Option value="0">不在用</Option>
                                    <Option value="1">在用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
            <span className={styles.sumbitButtons}>
              <AuthButton auth="category.search" type="primary" htmlType="submit">查询</AuthButton>
              <AuthButton auth="category.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</AuthButton>
            </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {
        const {rule: {loading: ruleLoading, data, categorySList}} = this.props;
        const {selectedRows, modalVisible, record, editType,recObjectVisible} = this.state;

        const menu = (
            <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
                <Menu.Item key="remove">删除</Menu.Item>
                <Menu.Item key="approval">批量审批</Menu.Item>
            </Menu>
        );

        return (
            <PageHeaderLayout title="商品分类管理">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <AuthButton auth="category.new" icon="plus" type="primary" onClick={() => this.handleAddCategory()}>新建</AuthButton>
                            {
                                selectedRows.length > 0 && (
                                    <span>
                    <Button>批量操作</Button>
                    <Dropdown overlay={menu}>
                      <Button>
                        更多操作 <Icon type="down"/>
                      </Button>
                    </Dropdown>
                  </span>
                                )
                            }
                        </div>
                        <GoodsCategoryTable
                            selectedRows={selectedRows}
                            loading={ruleLoading}
                            data={data}
                            key={new Date()}
                            onRecommendRow={this.handleRecommendRow}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleGoodsCategoryTableChange}
                            onDelRow={this.handleDelCategoryRow}
                            onEditRow={this.handleEditCategoryRow}
                        />
                    </div>
                </Card>
                <Modal
                    title="新建分类"
                    visible={modalVisible}
                    onOk={this.handleAdd}
                    key={new Date()}
                    onCancel={() => this.handleModalVisible()}
                    footer={null}
                >
                    <GoodsCategoryEdit ref="goodsCategoryEdit" pagination={data.pagination}
                                       editType={editType}
                                       record={record}
                                       categorySList={categorySList}
                                       handleModalVisible={this.handleModalVisible}
                                       handleModalSuccess={this.handleModalSuccess}
                    />
                </Modal>

                <Modal
                    title="新增推荐对象"
                    key={new Date()}
                    width={700}
                    visible={recObjectVisible}
                    onOk={this.handleRecObjectAdd}
                    onCancel={() => this.handlerecObjectVisible()}
                    footer={null}
                >
                    <RecObjectAdd  ref="recObjectAdd"
                                   pagination={data.pagination}
                                   editType={editType}
                                   record={record}
                                   type={4}
                        // categorySList={brandSList}
                                   handlerecObjectVisible={this.handlerecObjectVisible}
                                   returnRecObject={this.returnRecObject}
                    />
                </Modal>
            </PageHeaderLayout>
        );
    }
}
